<template>
    <div class="app-container">
        <vxe-grid ref="xGrid" v-bind="gridOptions" @checkbox-change="handleSelectionChange">
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button type="info" plain icon="Upload" @click="handleSyncMenu" v-hasPermi="['system:roleTable:syncDb']">同步</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleEditTable" v-hasPermi="['system:roleTable:edit']">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:roleTable:remove']">删除</el-button>
                    </el-col>
                </el-row>
            </template>
            <template #slotStatus="{ row }">
                <dict-tag :options="sys_common_status" :value="row.status" />
            </template>
            <template #action="{ row }">
                <el-tooltip content="编辑" placement="top">
                    <el-button link type="primary" icon="Edit" @click="handleEditTable(row)" v-hasPermi="['system:roleTable:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="同步" placement="top">
                    <el-button link type="primary" icon="Refresh" @click="handleSynchDb(row)" v-hasPermi="['system:roleTable:syncDb']"></el-button>
                </el-tooltip>
                <el-tooltip content="强制同步" placement="top">
                    <el-button link type="success" icon="Refresh" @click="handleForceSynchDb(row)" v-hasPermi="['system:roleTable:syncDb']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                    <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:roleTable:remove']"></el-button>
                </el-tooltip>
            </template>
        </vxe-grid>
    </div>
</template>

<script setup lang="ts" name="Gen">
    import { ref, getCurrentInstance, reactive, toRefs } from "vue";
    import { useRoute } from "vue-router";
    import router from "@/router";
    import { VxeGridInstance, VxeGridProps, VxeGridListeners } from "../../../../types/index";
    import XEUtils from "xe-utils";
    import useBaseApi from "@/api/base/index";
    import { syncMenu, synchDb, forceSynchDb } from "@/api/system/roleTable/table";
    import { removeObjectNull } from "@/utils";
    const route = useRoute();
    const { proxy } = getCurrentInstance() as any;
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const tableNames = ref([]);
    const data = reactive<any>({});
    const importRef = ref();
    const {} = toRefs(data);
    const { callPageList, callRemoves } = useBaseApi("/tableConfig/roleTable");
    const roleId = ref(route.params.roleId);
    const xGrid = ref({} as VxeGridInstance);

    const gridOptions = reactive<VxeGridProps>({
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "16",
        height: "auto",
        rowId: "tableId",
        sortConfig: {
            trigger: "cell",
            remote: true,
        },
        filterConfig: {
            remote: true,
        },
        pagerConfig: {
            pageSize: 10,
            pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
            perfect: true,
        },
        formConfig: {
            titleWidth: 80,
            titleAlign: "right",
            items: [
                {
                    field: "tableName",
                    title: "表名称",
                    span: 4,
                    itemRender: { name: "$input", props: { placeholder: "请输入表名称" } },
                },
                {
                    field: "tableComment",
                    title: "表描述",
                    span: 4,
                    itemRender: { name: "$input", props: { placeholder: "请输入表描述" } },
                },
                {
                    field: "createTime",
                    title: "创建时间",
                    span: 5,
                    itemRender: {
                        name: "ElDatePicker",
                        props: {
                            valueFormat: "YYYY-MM-DD",
                            type: "daterange",
                            rangeSeparator: "-",
                            startPlaceholder: "开始日期",
                            endPlaceholder: "结束日期",
                        },
                    },
                },
                {
                    itemRender: {
                        name: "$buttons",
                        children: [
                            {
                                props: {
                                    type: "submit",
                                    content: "查询",
                                    status: "primary",
                                },
                            },
                            {
                                props: {
                                    type: "reset",
                                    content: "重置",
                                },
                            },
                        ],
                    },
                },
            ],
        },
        toolbarConfig: {
            refresh: true,
            zoom: true,
            custom: true,
            slots: {
                buttons: "toolbar_buttons",
            },
        },
        proxyConfig: {
            paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
            seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
            sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
            filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
            form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
            // 对应响应结果 { result: [], page: { total: 100 } }
            props: {
                result: "rows", // 配置响应结果列表字段
                total: "total", // 配置响应结果总页数字段
            },
            ajax: {
                // 接收 Promise
                query: ({ page, sorts, filters, form, params }: any) => {
                    // 处理时间范围查询
                    const createTime = proxy.addDateRange({}, form.createTime, "createTime");
                    const queryParams: any = Object.assign({}, form, page, params);
                    // 处理排序条件
                    const orderByColumn = <Array<String>>[];
                    const isAsc = <Array<Boolean>>[];
                    sorts.forEach((m: any) => {
                        orderByColumn.push(m.field);
                        isAsc.push(m.order);
                    });
                    queryParams.orderByColumn = orderByColumn.join(",");
                    queryParams.isAsc = isAsc.join(",");
                    // 处理筛选条件
                    filters.forEach(({ property, values }: any) => {
                        queryParams[property] = values.join(",");
                    });
                    return callPageList({
                        ...removeObjectNull(queryParams),
                        roleId: roleId.value,
                    }).then((response) => {
                        return response;
                    });
                },
            },
        },
        radioConfig: {
            trigger: "row",
        },
        columns: [
            { type: "checkbox", width: 50 },
            {
                field: "roleTableId",
                title: "表格ID",
                width: 80,
            },
            {
                field: "tableName",
                title: "表名称",
                sortable: true,
            },
            {
                field: "tableComment",
                title: "表描述",
                sortable: true,
            },
            {
                field: "remark",
                title: "备注",
                sortable: true,
            },
            {
                field: "createBy",
                title: "创建者",
                sortable: true,
            },
            {
                field: "createTime",
                title: "创建时间",
                sortable: true,
                formatter({ cellValue }: any) {
                    return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                },
            },
            {
                field: "updateTime",
                title: "更新时间",
                sortable: true,
                formatter({ cellValue }: any) {
                    return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                },
            },
            {
                title: "操作",
                minWidth: 80,
                align: "center",
                fixed: "right",
                slots: { default: "action" },
            },
        ],
    });
    function handleQuery() {
        xGrid.value.commitProxy("reload");
    }
    /** 同步菜单数据 */
    function handleSyncMenu() {
        proxy.$modal.loading("加载中，请稍候...");
        syncMenu(roleId.value).then(() => {
            xGrid.value.commitProxy("reload");
            proxy.$modal.closeLoading();
            proxy.$modal.msgSuccess("操作成功");
        });
    }

    // 多选框选中数据
    function handleSelectionChange(selection: any) {
        ids.value = selection.records.map((item: any) => item.roleTableId);
        tableNames.value = selection.records.map((item: any) => item.tableName);
        single.value = selection.records.length != 1;
        multiple.value = !selection.records.length;
    }
    /** 修改按钮操作 */
    function handleEditTable(row: any) {
        const tableId = row.roleTableId || ids.value[0];
        router.push({
            path: "/system/role-edit-table/index/" + tableId,
        });
    }
    /** 删除按钮操作 */
    function handleDelete(row: any) {
        const tableIds = row.tableId || ids.value;
        proxy.$modal
            .confirm('是否确认删除表编号为"' + tableIds + '"的数据项？')
            .then(function () {
                return callRemoves(tableIds);
            })
            .then(() => {
                xGrid.value.commitProxy("reload");
                proxy.$modal.msgSuccess("删除成功");
            })
            .catch(() => {});
    }
    /** 同步数据库操作 */
    function handleSynchDb(row: any) {
        const tableName = row.tableName;
        const tableId = row.tableId;
        const roleTableId = row.roleTableId;
        const menuId = row.menuId;
        const roleId = row.roleId;
        proxy.$modal
            .confirm('同步只会添加角色表格配置中不存在菜单表格配置中的数据，确认要同步"' + tableName + '"表结构吗？')
            .then(function () {
                return synchDb({
                    menuId,
                    roleTableId,
                    tableId,
                    roleId,
                });
            })
            .then(() => {
                proxy.$modal.msgSuccess("同步成功");
            })
            .catch(() => {});
    }
    /** 强制同步数据库操作*/
    function handleForceSynchDb(row: any) {
        const tableName = row.tableName;
        const tableId = row.tableId;
        const roleTableId = row.roleTableId;
        const menuId = row.menuId;
        const roleId = row.roleId;
        proxy.$modal
            .confirm('强制同步会更新已存在的数据，并且添加不存在的数据，确认要强制同步"' + tableName + '"表结构吗？')
            .then(function () {
                return forceSynchDb({
                    menuId,
                    roleTableId,
                    tableId,
                    roleId,
                });
            })
            .then(() => {
                proxy.$modal.msgSuccess("同步成功");
            })
            .catch(() => {});
    }
</script>
